import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, computed } from 'vue'
import dayjs from 'dayjs'

export const useObserver = apiFn => {
  // 通过 ref 获得组件实例
  const target = ref(null)
  // target 是观察的目标dom容器，必须是dom容器，而且是vue3.0方式绑定的dom对象
  const { stop } = useIntersectionObserver(
    target,
    // isIntersecting 是否进入可视区域，true是进入 false是移出
    // observerElement 被观察的dom
    ([{ isIntersecting }], observerElement) => {
      // 在此处可根据isIntersecting来判断，然后做业务
      // 进入可视区域了
      if (isIntersecting) {
        // 停止监听
        stop()
        apiFn()
      }
    }
  )

  return target
}

/**
 * 倒计时功能
 * @param {*} count 倒计时总长度（单位：秒）
 */
export const useCountDown = (count = 60) => {
  const countTime = ref(0)

  const countTimeText = computed(() => {
    return dayjs.unix(countTime.value).format('mm分ss秒')
  })

  const { pause, resume } = useIntervalFn(() => {
    if (countTime.value <= 1) {
      return
    }

    countTime.value--
  }, 1000)

  // 开始
  const start = newStartCount => {
    countTime.value = newStartCount || count
  }

  return {
    countTime,
    countTimeText,
    start,
    pause,
    resume
  }
}
